//
//  TestPlanDataViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/7/10.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "TestPlanDataViewController.h"
#import "ChildListCell.h"
#import "PersonDataViewController.h"
#import "DSectionIndexItemView.h"
#import "DSectionIndexView.h"
@interface TestPlanDataViewController ()<DSectionIndexViewDelegate,DSectionIndexViewDataSource,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableDictionary * allDataDictionary;
@property(nonatomic,assign)NSInteger joinProNumber;
@property (strong, nonatomic) DSectionIndexView * sectionIndexView;
@end

@implementation TestPlanDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"测试计划信息";
    self.view.backgroundColor = UIColorFromRGB(241, 246, 248);
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont boldSystemFontOfSize:23*AutoScaleHorizontal],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    ////////////////左按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 35,35);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    
}
-(void)leftBarBtnClicked{
    NSLog(@"左按钮");
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}

#pragma mark 获取数据
-(void)getData{
    
    self.childArray = [[NSMutableArray alloc]initWithCapacity:0];
    self.ZiMuArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.ZiMuPaiXuArr = [[NSMutableArray alloc]initWithCapacity:0];
    NSMutableArray * newPaixuArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //获取全部数据
    NSString* str = [user objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    //循环遍历看有多少人参加了现有的计划
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];
    NSMutableArray * childArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"ChildList"]];
    
    _joinProNumber = 0;
//    for (NSMutableDictionary * childDic in childArray) {
    
        
        for (NSDictionary * dict in testArray) {
            NSDictionary * masterdic = [dict objectForKey:@"master"];
            
//            if ([[childDic objectForKey:@"Id"]isEqual:[masterdic objectForKey:@"ChildId"]]) {
            
                if ([[masterdic objectForKey:@"ProgramId"]isEqual:self.planModel.Id]) {
                    _joinProNumber += 1;
                    ChildModel * model = [ChildModel modelWithDictionary:masterdic];
                    [newPaixuArr addObject:model];
                }
            }
//        }
//    }

    NSMutableArray * childArr = [[NSMutableArray alloc]initWithCapacity:0];//准备对孩子名字排序的数组,放孩子名
    for (ChildModel * mod in newPaixuArr) {
        [childArr addObject:mod.ChildName];
    }
    self.ZiMuArr = [ChineseString IndexArray:childArr];
    [self.ZiMuArr insertObject:@"☆" atIndex:0];
    self.ZiMuPaiXuArr = [ChineseString LetterSortArray:childArr];
    //将模型数组从新排序
    for (NSMutableArray* array in self.ZiMuPaiXuArr) {
        NSMutableArray * smallArray = [[NSMutableArray alloc]initWithCapacity:0];
        for (NSString*str in array) {
            for (ChildModel*mod in newPaixuArr.reverseObjectEnumerator) {
                if ([str isEqualToString:mod.ChildName]) {
                    [smallArray addObject: mod];
                    [newPaixuArr removeObject:mod];
                }
            }
        }
        [self.childArray addObject:smallArray];
    }
    [user synchronize];
    
    [self creatUI];
}

-(void)creatUI{

    //创建列表
    //有数据时创建列表
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(75, 0, SCREEN_WIDTH-150, SCREEN_HEIGHT-100) style:UITableViewStyleGrouped];
    self.myTableView.backgroundColor =UIColorFromRGB(241, 244, 248);
    self.myTableView.delegate =self;
    self.myTableView.dataSource =self;
    self.myTableView.showsVerticalScrollIndicator =NO;
    //无分割线
    //    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //多余的CELL 隐藏
    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.myTableView registerClass:[ChildListCell class] forCellReuseIdentifier:@"ChildListCell"];
    [self.view addSubview:self.myTableView];
    
    [self _initIndexView];
}

#define kSectionIndexWidth 40.f
#define kSectionIndexHeight 460.f
- (void)_initIndexView
{
    _sectionIndexView = [[DSectionIndexView alloc] init];
    _sectionIndexView.backgroundColor = [UIColor clearColor];
    _sectionIndexView.dataSource = self;
    _sectionIndexView.delegate = self;
    _sectionIndexView.isShowCallout = YES;
    _sectionIndexView.calloutViewType = CalloutViewTypeForUserDefined;
    _sectionIndexView.calloutDirection = SectionIndexCalloutDirectionLeft;
    _sectionIndexView.calloutMargin = 100.f;
    [self.view addSubview:self.sectionIndexView];
    [_sectionIndexView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.myTableView.mas_right).with.offset(15*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.myTableView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(kSectionIndexWidth, kSectionIndexHeight));
    }];
    [self.sectionIndexView reloadItemViews];
}

#pragma mark tableViewDelegate

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView * view = [[UIView alloc]init];
        view.backgroundColor = [UIColor clearColor];
    
        self.whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, 25*AutoScaleVertical, self.myTableView.frame.size.width, 150*AutoScaleVertical)];
        self.whiteView.layer.cornerRadius = 10;
        self.whiteView.layer.masksToBounds = YES;
        self.whiteView.backgroundColor = [UIColor whiteColor];
        [view addSubview:self.whiteView];
//        [self.whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(view.mas_top).with.offset(25*AutoScaleVertical);
//            make.left.mas_equalTo(self.myTableView.mas_left);
//            make.right.mas_equalTo(self.myTableView.mas_right);
//            make.height.mas_equalTo(150*AutoScaleVertical);
//        }];
        
        self.planNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(45*AutoScaleHorizontal, 30*AutoScaleVertical, 700*AutoScaleHorizontal, 20*AutoScaleVertical)];
        self.planNameLabel.textColor = [UIColor blackColor];
        self.planNameLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
        self.planNameLabel.text = self.planModel.Title;
        [self.whiteView addSubview:self.planNameLabel];
//        [self.planNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(self.whiteView.mas_left).with.offset(45*AutoScaleHorizontal);
//            make.top.mas_equalTo(self.whiteView.mas_top).with.offset(30*AutoScaleVertical);
//            make.size.mas_equalTo(CGSizeMake(700*AutoScaleHorizontal, 20*AutoScaleVertical));
//        }];
        
        self.teacherNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(45*AutoScaleHorizontal, 75*AutoScaleVertical, 250*AutoScaleHorizontal, 20*AutoScaleVertical)];
        self.teacherNameLabel.textColor = [UIColor blackColor];
        self.teacherNameLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
        self.teacherNameLabel.text = self.planModel.CreateTeacher;
        [self.whiteView addSubview:self.teacherNameLabel];
//        [self.teacherNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(self.whiteView.mas_left).with.offset(45*AutoScaleHorizontal);
//            make.top.mas_equalTo(self.planNameLabel.mas_bottom).with.offset(25*AutoScaleVertical);
//            make.size.mas_equalTo(CGSizeMake(250*AutoScaleHorizontal, 20*AutoScaleVertical));
//        }];
        
        self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(300*AutoScaleHorizontal, 75*AutoScaleVertical, 300*AutoScaleHorizontal, 20*AutoScaleVertical)];
        self.timeLabel.textColor = [UIColor blackColor];
        self.timeLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
        self.timeLabel.text = [NSString stringWithFormat:@"创建时间%@", [self.planModel.CreateTime substringWithRange:NSMakeRange(0, 10)]];
        [self.whiteView addSubview:self.timeLabel];
//        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(self.teacherNameLabel.mas_right);
//            make.top.mas_equalTo(self.teacherNameLabel.mas_top);
//            make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 20*AutoScaleVertical));
//        }];
        
        //共多少人
        self.numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 230*AutoScaleVertical, 150*AutoScaleHorizontal, 20*AutoScaleVertical)];
        self.numberLabel.textColor = [UIColor blackColor];
        self.numberLabel.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
        self.numberLabel.text= [NSString stringWithFormat:@"共%d人",self.joinProNumber];
        [view addSubview:self.numberLabel];
//        [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.whiteView.mas_bottom).with.offset(50*AutoScaleVertical);
//            make.left.mas_equalTo(self.myTableView.mas_left).with.offset(75*AutoScaleHorizontal);
//            make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 20*AutoScaleVertical));
//        }];
        return view;
    }else{
        return nil;
    }
}

//-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    return self.ZiMuArr;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section ==0 ) {
        return 250*AutoScaleVertical;
    }else{
        return 20*AutoScaleVertical;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section ==0) {
        return nil;
    }else{
        NSString *key = [self.ZiMuArr objectAtIndex:section];
        return key;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.ZiMuPaiXuArr.count+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section ==0) {
        return 0;
    }else{
        return [[self.ZiMuPaiXuArr objectAtIndex:section-1] count];
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        return nil;
    }
    ChildListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ChildListCell"];
    //cell.userInteractionEnabled = NO;
    if (cell == nil) {
        cell = [[ChildListCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier: @"MainViewCell"] ;
    }
    
    [cell relayoutUIWithModel:self.childArray[indexPath.section-1][indexPath.row]];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%d",indexPath.row);
    PersonDataViewController * vc = [[PersonDataViewController alloc]init];
    vc.planmodel = self.planModel;
    vc.model = self.childArray[indexPath.section-1][indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark DSectionIndexViewDataSource && delegate method
- (NSInteger)numberOfItemViewForSectionIndexView:(DSectionIndexView *)sectionIndexView
{
    return self.myTableView.numberOfSections;
}

- (DSectionIndexItemView *)sectionIndexView:(DSectionIndexView *)sectionIndexView itemViewForSection:(NSInteger)section
{
    
    //    if (section == 0) {
    //        return nil;
    //    }else{
    DSectionIndexItemView *itemView = [[DSectionIndexItemView alloc] init];
    
    itemView.titleLabel.text = [self.ZiMuArr objectAtIndex:section ];
    itemView.titleLabel.font = [UIFont systemFontOfSize:12];
    itemView.titleLabel.textColor = UIColorFromRGB(28, 173, 146);
    itemView.titleLabel.highlightedTextColor = [UIColor redColor];
    itemView.titleLabel.shadowColor = [UIColor whiteColor];
    itemView.titleLabel.shadowOffset = CGSizeMake(0, 1);
    
    return itemView;
    //    }
}

- (UIView *)sectionIndexView:(DSectionIndexView *)sectionIndexView calloutViewForSection:(NSInteger)section
{
    
    
    //    if (section == 0) {
    //        return nil;
    //    }else{
    UILabel *label = [[UILabel alloc] init];
    
    label.frame = CGRectMake(512, 192, 80*AutoScaleHorizontal, 80*AutoScaleVertical);
    
    
    label.backgroundColor = [UIColor clearColor];
    label.textColor = UIColorFromRGB(28, 173, 146);
    label.font = [UIFont boldSystemFontOfSize:36];
    label.text = [self.ZiMuArr objectAtIndex:section];
    label.textAlignment = UITextAlignmentCenter;
    
    [label.layer setCornerRadius:label.frame.size.width/2];
    [label.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [label.layer setBorderWidth:3.0f];
    [label.layer setShadowColor:[UIColor blackColor].CGColor];
    [label.layer setShadowOpacity:0.8];
    [label.layer setShadowRadius:5.0];
    [label.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
    
    
    return label;
    //    }
}

- (NSString *)sectionIndexView:(DSectionIndexView *)sectionIndexView
               titleForSection:(NSInteger)section
{
    
    //    if (section == 0) {
    //        return nil;
    //    }else{
    return [self.ZiMuArr objectAtIndex:section];
    //    }
}

- (void)sectionIndexView:(DSectionIndexView *)sectionIndexView didSelectSection:(NSInteger)section
{
    
    if (section == 0) {
        NSLog(@"过了");
        [self.myTableView setContentOffset:CGPointMake(0,0) animated:YES];
    }else{
        [self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
